/**
 * There are code generation
 */
package com.neusoft.lohas.modules.ivm.dao.order;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.neusoft.lohas.common.persistence.BaseDao;
import com.neusoft.lohas.common.persistence.Parameter;
import com.neusoft.lohas.common.utils.FloatFormat;
import com.neusoft.lohas.common.utils.StringUtils;
import com.neusoft.lohas.modules.ivm.entity.order.Order;
import com.neusoft.lohas.modules.ivm.entity.order.OrderDetail;
import com.neusoft.lohas.modules.ivm.entity.product.ProductInventoryDetail;
import com.neusoft.lohas.modules.ivm.entity.product.ProductRelation;
import com.neusoft.lohas.modules.ivm.entity.purchase.PurchaseDetail;
import com.neusoft.lohas.modules.ivm.entity.purchase.PurchaseDetailItem;

/**
 * 商品订单DAO接口
 * @author Jackie.Liu
 * @version 2014-12-16
 */
@Repository
public class OrderDao extends BaseDao<Order> {
	
	public Order findByOrderNo(String orderNo){
		return getByHql("from Order where orderNo = :p1", new Parameter(orderNo));
	}

	public int updateStatusById(String orderId, String status) {
		if(status.equals("2")){//如果流程完成，则同时更新订单的支付状态
			return update("update Order set orderType=:p1, payStatus=:p2 where id = :p3", new Parameter(status,"1",orderId));
		}
		return update("update Order set orderType=:p1 where id = :p2", new Parameter(status, orderId));
	}
	
	public int finishOrder(String id){
		return update("update Order set orderType=:p1, payStatus=:p2 where id = :p3", new Parameter("2","1",id));
	}

	/*
	 * 更新用户领奖状态
	 */
	public void updateScanType(String mobile, int type) {
		String sql = "update ievent.ex_scan e, ievent.u_info u set e.state="+type+" where e.userId=u.userId and u.mobileNo="+mobile;
		updateBySql(sql, new Parameter());
	}
	
	public int getOrderNumsByDate(String merchantId){
		String sql = "select count(*) from ivm_order where date(create_date) = date(now()) and merchant_id='"+merchantId+"'";
		List<Object> list = findBySql(sql, new Parameter());
		if(list == null){
			return 1;
		}
		return Integer.valueOf(list.get(0).toString());
	}
	
	/**
	 * 用户生成采购清单操作的查询封装
	 * @param orderIds
	 * @param type=1生成采购清单，type=2生成配货清单
	 * @return
	 */
	public List<PurchaseDetail> getOrderPurchaseList(String orderIds, String supplierId, int purchaseState, int type) {
		String sql = "select * from ivm_order where id in("+orderIds+") and del_flag=:p1";
		List<PurchaseDetail> result = new ArrayList<PurchaseDetail>();
		List<Order> list = findBySql(sql, new Parameter(Order.DEL_FLAG_NORMAL), Order.class);
		for (Order order : list) {
			for (OrderDetail orderDetail : order.getDetailList()) {
//				boolean isExists = false;
//				if (result.size()>0) {
//					for (PurchaseDetail bean : result) {
//						if (bean.getProduct().getId().equals(orderDetail.getProduct().getId())) {
//							isExists = true; 
//							bean.setBuyNumber((bean.getBuyNumber()+orderDetail.getNumber())*bean.getProduct().getProductUnit().getNumber());
//							bean.setPurchaseNumber(-1*(bean.getProduct().getStock()-bean.getBuyNumber()));
//							break;
//						}
//					}
//				}
//				if (!isExists) {  //如果当前result已经存在了该商品清单,则在其基础上累加购买量
					if(StringUtils.isNotBlank(supplierId) && (orderDetail.getProduct().getDefaultSupplier()==null || !orderDetail.getProduct().getDefaultSupplier().getId().equals(supplierId))){
						continue;
					}
					//如果商品是礼包，并且是生成采购清单，则进行拆分
					if(orderDetail.getProduct().getProProperty().equals("1") && type==1){
						int num = orderDetail.getNumber();//购买礼包数量
						for(ProductRelation relation : orderDetail.getProduct().getRelationList()){
							PurchaseDetail detail = new PurchaseDetail();
							//查询商户中该商品对应的采购指令信息
							sql = "select a.* from ivm_purchase_detail a inner join ivm_purchase_detail_order b on a.id=b.purchase_detail_id inner join ivm_purchase c on a.purchase_id=c.id where c.state=0 and a.merchant_id=:p1 and a.product_id=:p2 and b.order_id=:p3 and a.del_flag=:p4";
							List<PurchaseDetail> pdlist = findBySql(sql, new Parameter(orderDetail.getMerchant().getId(), relation.getProduct().getId(), order.getId(), PurchaseDetail.DEL_FLAG_NORMAL), PurchaseDetail.class);
							if((purchaseState==1 && pdlist.size()==0) || (purchaseState==2 && pdlist.size()>0)){ //已经生成采购指令清单
								continue;
							}
							if (pdlist.size()>0) {
								detail.setPurchase(pdlist.get(0).getPurchase());
								//获取采购指令明细（不合并生成的明细）对应的商品采购数量
								sql = "select * from ivm_purchase_detail_item where merchant_id=:p1 and order_id=:p2 and product_id=:p3 and purchase_id=:p4 and del_flag=:p5";
								List<PurchaseDetailItem> pdilist = findBySql(sql, new Parameter(relation.getMerchant().getId(), order.getId(), relation.getProduct().getId(), detail.getPurchase().getId(), PurchaseDetailItem.DEL_FLAG_NORMAL), PurchaseDetailItem.class);
								if (pdilist.size()>0) {
									detail.setPurchaseNumber(pdilist.get(0).getPurchaseNumber());
								}
							}else {
								detail.setPurchaseNumber(relation.getNum()*relation.getProduct().getSpecNum()*num);
								//detail.setPurchaseNumber(orderDetail.getNumber());
							}
							List<ProductInventoryDetail> inventoryDetailList = relation.getProduct().getInventoryDetailList();
							detail.setMerchant(relation.getMerchant());
							detail.setProduct(relation.getProduct());
							detail.setBuyNumber(relation.getNum()*num);
							if (inventoryDetailList.size()>0) {
								ProductInventoryDetail inventoryDetail = inventoryDetailList.get(inventoryDetailList.size()-1);
								if(inventoryDetail.getWeight() != 0){
									detail.setReferencePrice(FloatFormat.m2_2(relation.getProduct().getSpecNum()*inventoryDetail.getAmount()/inventoryDetail.getWeight()));
								}
							}
							detail.setOrder(order);
							result.add(detail);
						}
					}else{
						PurchaseDetail detail = new PurchaseDetail();
						//查询商户中该商品对应的采购指令信息
						sql = "select a.* from ivm_purchase_detail a inner join ivm_purchase_detail_order b on a.id=b.purchase_detail_id inner join ivm_purchase c on a.purchase_id=c.id where c.state=0 and a.merchant_id=:p1 and a.product_id=:p2 and b.order_id=:p3 and a.del_flag=:p4";
						List<PurchaseDetail> pdlist = findBySql(sql, new Parameter(orderDetail.getMerchant().getId(), orderDetail.getProduct().getId(), order.getId(), PurchaseDetail.DEL_FLAG_NORMAL), PurchaseDetail.class);
						if((purchaseState==1 && pdlist.size()==0) || (purchaseState==2 && pdlist.size()>0)){ //已经生成采购指令清单
							continue;
						}
						if (pdlist.size()>0) {
							detail.setPurchase(pdlist.get(0).getPurchase());
							//获取采购指令明细（不合并生成的明细）对应的商品采购数量
							sql = "select * from ivm_purchase_detail_item where merchant_id=:p1 and order_id=:p2 and product_id=:p3 and purchase_id=:p4 and del_flag=:p5";
							List<PurchaseDetailItem> pdilist = findBySql(sql, new Parameter(orderDetail.getMerchant().getId(), order.getId(), orderDetail.getProduct().getId(), detail.getPurchase().getId(), PurchaseDetailItem.DEL_FLAG_NORMAL), PurchaseDetailItem.class);
							if (pdilist.size()>0) {
								detail.setPurchaseNumber(pdilist.get(0).getPurchaseNumber());
							}
						}else {
							detail.setPurchaseNumber(orderDetail.getNumber()*orderDetail.getProduct().getSpecNum());
							//detail.setPurchaseNumber(orderDetail.getNumber());
						}
						List<ProductInventoryDetail> inventoryDetailList = orderDetail.getProduct().getInventoryDetailList();
						detail.setMerchant(orderDetail.getMerchant());
						detail.setProduct(orderDetail.getProduct());
						detail.setBuyNumber(orderDetail.getNumber());
						if (inventoryDetailList.size()>0) {
							ProductInventoryDetail inventoryDetail = inventoryDetailList.get(inventoryDetailList.size()-1);
							if(inventoryDetail.getWeight() != 0){
								detail.setReferencePrice(FloatFormat.m2_2(orderDetail.getProduct().getSpecNum()*inventoryDetail.getAmount()/inventoryDetail.getWeight()));
							}
						}
						detail.setOrder(order);
						result.add(detail);
					}
//				}
			}
		}
		//排序
		Collections.sort(result, new Comparator<PurchaseDetail>() {
			@Override
            public int compare(PurchaseDetail arg0, PurchaseDetail arg1) {
					return arg0.getProduct().getCode().compareTo(arg1.getProduct().getCode());
            }
        });
		return result;
	}
	
}
